<?php


namespace app\admin\controller;


use app\admin\model\CommunityModel;
use app\admin\model\RoleUserModel;
use app\admin\model\StoreModel;
use app\admin\model\UserModel;
use app\admin\model\UserRoleModel;
use cmf\controller\AdminBaseController;
use think\Validate;
use think\facade\Env;

class CommunityController extends AdminBaseController
{
    public function index()
    {
        $admin_id = cmf_get_current_admin_id();
        $role_id = RoleUserModel::where('user_id', $admin_id)->value('role_id');
        $role_id = $role_id ? $role_id : 1;
        $this->assign('role_id', $role_id);
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            $page = isset($data['page']) && $data['page'] ? $data['page'] : 1;

            $admin_id = cmf_get_current_admin_id();
            $admin_user_info = UserModel::get($admin_id);
            $where = [];
            if (isset($data['region'])) {
                $where[] = ['region', 'eq', json_encode($data['region'])];
            }
            if (isset($data['keyword'])) {
                $where[] = ['name', 'like', '%' . $data['keyword'] . '%'];
            }
            if ($admin_user_info['company_id']) {
                $company_id = $admin_user_info['company_id'];
            }else{
                $company_id = isset($data['company_id']) && $data['company_id'] ? $data['company_id'] : 0;
            }
            if($company_id){
                $where[] = ['company_id', '=', $company_id];
            }

            $list = CommunityModel::with('company_info')->where($where)
                ->order('create_at desc')
                ->paginate(10, false, ['page' => $page])->each(function ($item) {
                    if ($item['region']) {
                        $item['region'] = json_decode($item['region']);
                    }
                    return $item;
                });
            $this->success('', '', $list);
        }
        $cityFilePath = Env::get('root_path') . 'public/plugins/pca.json';
        //$cityFilePath = Env::get('root_path') . 'public/static/city.json';
        $cityFile = fopen($cityFilePath, "r");
        $city = json_decode(fread($cityFile, filesize($cityFilePath)));
        $arr = [];
        foreach ($city as $k => $v) {
            $one_arr = [
                'value' => $k,
                'label' => $k,
                'children' => [],
            ];
            foreach ($v as $a => $b) {
                $two_arr = [
                    'value' => $a,
                    'label' => $a,
                    'children' => [],
                ];
                foreach ($b as $c => $d) {
                    $three_arr = [
                        'value' => $d,
                        'label' => $d,
                    ];
                    array_push($two_arr['children'], $three_arr);
                }
                array_push($one_arr['children'], $two_arr);
            }
            array_push($arr, $one_arr);
        }
        //dump($arr);die;
        fclose($cityFile);
        $this->assign('city', json_encode($arr));
        return $this->fetch();
    }

    public function update()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $validate = new Validate([
                'name' => 'require',
            ]);
            $validate->message([
                'name.require' => '请输入小区名称',
            ]);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $admin_id = cmf_get_current_admin_id();
            $admin_user_info = UserModel::get($admin_id);
            if ($admin_user_info['company_id']) {
                $company_id = $admin_user_info['company_id'];
            } else {
                $company_id = isset($data['company_id']) && $data['company_id'] ? $data['company_id'] : '';
            }
            if (empty($company_id)) {
                $this->error('请选择公司');
            }
            if (isset($data['id']) && $data['id']) {
                $community_model = CommunityModel::get($data['id']);

                if ($community_model->region != json_encode($data['region']) || $community_model->name != $data['name']) {
                    $find = CommunityModel::get(['region' => $data['region'], 'name' => $data['name'], 'company_id' => $company_id]);
                    if ($find) {
                        $this->error('此地区的该小区名已存在');
                    }
                }
                $community_model->company_id = $company_id;
                $community_model->name = $data['name'];
                $community_model->region = json_encode($data['region']);
                $res = $community_model->save();
            } else {
                $data['region'] = json_encode($data['region']);
                $data['company_id'] = $company_id;
                $find = CommunityModel::get(['region' => $data['region'], 'name' => $data['name'], 'company_id' => $company_id]);
                if ($find) {
                    $this->error('此地区的该小区名已存在');
                }

                $res = CommunityModel::create($data);
            }

            if ($res) {
                $this->success('添加成功');
            } else {
                $this->error('添加失败');
            }
        }
    }

    public function get_store_by_company_id()
    {
        $data = $this->request->param();
        $company_id = isset($data['company_id']) && $data['company_id'] ? $data['company_id'] : 0;
        $list = StoreModel::where('company_id', $company_id)->all();
        $role_list = UserRoleModel::where('company_id', $company_id)->all();
        $manager_list = UserModel::where(['company_id' => $company_id, 'role_name' => '业务经理'])
            ->where(['user_type' => 2, 'is_delete' => 0])
            ->order('create_time desc')
            ->all()->each(function ($item) {
                $item['name'] = $item['true_name'] . '(' . $item['role_name'] . ')';
                return $item;
            });
        $this->success($company_id, '', ['store_list' => $list, 'role_list' => $role_list, 'manager_list' => $manager_list]);
    }

    public function delete()
    {
        $model = StoreModel::withCount(['user_list' => function ($query) {
            $query->where('is_delete', 0);
        }])->get(input('post.id'));
        if ($model) {
            if ($model['user_list_count'] > 0) {
                $this->error('该店铺下还有未删除用户');
            }
            $res = $model->delete();
            if ($res) {
                $this->success('ok');
            } else {
                $this->error('fail');
            }
        } else {
            $this->error('数据异常');
        }
    }
}
